package cn.kgc.ssm.web.intercepters;

import cn.hutool.json.JSONUtil;
import cn.kgc.ssm.web.response.ResponseResult;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/8/6
 * @description  非法请求拦截器
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        if (ObjectUtils.isEmpty(user)){
            // 返回json格式数据
            response.setContentType("application/json;charset=utf-8");
            ResponseResult message = ResponseResult.fail().code(401).message("请认证后访问...");

            PrintWriter writer = response.getWriter();
            writer.write(JSONUtil.toJsonStr(message));
            writer.close();
            return  false;
        }

        return true;
    }
}
